/**
 * 
 */
package com.cms.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cms.model.Category;
import com.cms.service.CategoryService;
import com.cms.service.CategoryServiceImpl;
import com.util.Singleton;

/**
 * @author jinmei.wang
 *
 */
public class CategoryManager extends Singleton {
	
	private CategoryService service = null;
	private Map<Integer, Category> map = null;
	private List<Category> list = null;
	
	public static void main (String[] argv)
	{
	}
	
	public static CategoryManager getInstance()
	{
		return (CategoryManager) CategoryManager.getInstance(CategoryManager.class.getName());
	}
	public CategoryManager()
	{
		map = new HashMap<Integer, Category>();
		list = new ArrayList<Category>();
		service = new CategoryServiceImpl();
		for (Category p : service.getCategory())
		{
			map.put(p.getId(), p);
			list.add(p);
		}
	}
	
	public Category getCategory(int id)
	{
		return map.get(id);
	}
	
	public List<Category> getCategorys()
	{
		return list;
	}
	
	public boolean saveCpInfo(String type, Category model)
	{
			if (type.equals("insert"))
			{
				if(service.saveCategory(model))
				{
					map.put(model.getId(), model);
					list.add(model);
					return true;
				}
			}
			else if (type.equals("delete"))
			{
				if(service.deleteCategory(model))
				{
					map.remove(model.getId());
					for (int n = 0; n < list.size(); n++)
					{
						if (list.get(n).getId() == model.getId())
						{
							list.remove(n);
							break;
						}
					}
					return true;
				}
			}
			else 
			{
				if(service.updateCategory(model))
				{
					model = service.getCategoryById(model);
					map.put(model.getId(), model);
					for (int n = 0; n < list.size(); n++)
					{
						if (list.get(n).getId() == model.getId())
						{
							list.set(n, model);
							break;
						}
					}
					return true;
				}
			}
			return false;
	}
	
}
